package org.firefly.repository;

import jakarta.persistence.LockModeType;
import org.firefly.entity.TimeCapsule;
import org.firefly.entity.TimeCapsule.CapsuleType;
import org.firefly.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Repository
public interface TimeCapsuleRepository extends JpaRepository<TimeCapsule, Long> {
    // 根据用户查找
    List<TimeCapsule> findByUser(User user);

    // 根据用户、未开启且开启时间在之后查找
    List<TimeCapsule> findByUserAndOpenedFalseAndOpenDateAfter(User user, LocalDateTime date);

    // 根据开启时间区间和未开启查找
    List<TimeCapsule> findByOpenDateBetweenAndOpenedFalse(LocalDateTime start, LocalDateTime end);

    // 根据类型和未开启状态查询
    List<TimeCapsule> findByTypeAndOpenedFalse(CapsuleType type);

    // 根据开启时间之前和未开启查找
    List<TimeCapsule> findByOpenDateBeforeAndOpenedFalse(LocalDateTime date);

    // 根据ID和用户查找
    Optional<TimeCapsule> findByIdAndUser(Long id, User user);

    // 新增方法
    List<TimeCapsule> findByOpenedFalse();

    // 带锁查询（可选）
    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("SELECT t FROM TimeCapsule t WHERE t.id = :id")
    Optional<TimeCapsule> findByIdWithLock(@Param("id") Long id);
}